# app/geo.py
import exifread
from pathlib import Path

def _dms_to_deg(values):
    d = values[0].num / values[0].den
    m = values[1].num / values[1].den
    s = values[2].num / values[2].den
    return d + m/60 + s/3600

def read_gps_from_image(image_path: str):
    """返回 (lat, lon) 或 (None, None)"""
    p = Path(image_path)
    if not p.exists():
        return None, None
    with p.open("rb") as f:
        tags = exifread.process_file(f, details=False)
    lat_tag = tags.get("GPS GPSLatitude")
    lon_tag = tags.get("GPS GPSLongitude")
    if not lat_tag or not lon_tag:
        return None, None
    lat = _dms_to_deg(lat_tag.values)
    lon = _dms_to_deg(lon_tag.values)
    lat_ref = str(tags.get("GPS GPSLatitudeRef", "N")).upper()
    lon_ref = str(tags.get("GPS GPSLongitudeRef", "E")).upper()
    if lat_ref == "S":
        lat = -lat
    if lon_ref == "W":
        lon = -lon
    return lat, lon

def feature_point(lon: float, lat: float, props: dict | None = None):
    return {
        "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [lon, lat]},
        "properties": props or {}
    }

def feature_collection(features: list[dict]):
    return {"type": "FeatureCollection", "features": features}
